/*
 * @Author: silence
 * @Date: 2022-11-25 10:48:57
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2022-11-26 22:22:34
 * @Description: 查看视频（本地、远程）
 */

import 'dart:io';

import 'package:bot_toast/bot_toast.dart';
import 'package:demo_trtc_live/config.dart';
import 'package:demo_trtc_live/utils/TrtcUtils.dart';
import 'package:flutter/material.dart';
import 'package:my_alert_dialog_package/my_alert_dialog_package.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_def.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_listener.dart';
import 'package:tencent_trtc_cloud/trtc_cloud_video_view.dart';

class ShowVideoPage extends StatefulWidget {
  const ShowVideoPage({Key? key}) : super(key: key);

  @override
  State<ShowVideoPage> createState() => _ShowVideoPageState();
}

class _ShowVideoPageState extends State<ShowVideoPage> {
  int quality = TRTCCloudDef.TRTC_AUDIO_QUALITY_DEFAULT;

  @override
  void initState() {
    super.initState();

    // 获取摄像头权限、麦克风权限
    _cameraPermissions().then((value) => _microPermissions());

    TrtcUtils.onRtcListener = (type, param) {
      if (type == TRTCCloudListener.onRemoteUserEnterRoom) {
        BotToast.showText(text: '有用户进来了');
      }

      if (type == TRTCCloudListener.onRemoteUserLeaveRoom) {
        BotToast.showText(text: '有用户退出房间了');
      }
    };

    // 开启声音
    if (Platform.isIOS) TrtcUtils.trtcCloud?.startLocalAudio(quality);
  }

  Future<void> _cameraPermissions() async {
    if (await Permission.camera.request().isDenied ||
        await Permission.camera.isDenied) {
      showPermission(context,
          title: "相机访问权限没有开启", message: "请到系统设置页面，打开相机访问权限");
      return;
    }
  }

  Future<void> _microPermissions() async {
    if (await Permission.microphone.request().isDenied ||
        await Permission.microphone.isDenied) {
      showPermission(context,
          title: "麦克风权限没有开启", message: "请到系统设置页面，打开麦克风访问权限");
      return;
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('视频会议中...')),
      body: Column(children: [
        Expanded(
          child: itemContainer(
              title: Platform.isAndroid ? '我[前置摄像头]' : '我[后置摄像头]',
              child: localVideoWidget()),
          flex: 1,
        ),
        SizedBox(
          height: 20,
        ),
        Expanded(
            child: itemContainer(
                title: Platform.isAndroid ? '对方[前置摄像头]' : '对方[后置摄像头]',
                child: remoteVideoWidget()),
            flex: 1)
      ]),
    );
  }

  itemContainer({String? title, Widget? child}) {
    return Stack(
      children: [
        child ?? Container(),
        Positioned(
            left: 10,
            top: 10,
            child: Text(
              title ?? "",
              style: TextStyle(color: Colors.red),
            )),
      ],
    );
  }

  /// 加载本地视频镜像
  localVideoWidget() {
    return TRTCCloudVideoView(onViewCreated: (viewId) {
      if (TrtcUtils.trtcCloud != null) {
        TrtcUtils.trtcCloud!
            .startLocalPreview(Platform.isAndroid ? true : false, viewId);
      }
    });
  }

  /// 加载远程视频镜像
  remoteVideoWidget() {
    return TRTCCloudVideoView(onViewCreated: (viewId) {
      if (TrtcUtils.trtcCloud != null) {
        TrtcUtils.trtcCloud!.startRemoteView(
            Config.userId2, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_SMALL, viewId);
      }
    });
  }

  roomVideoWidget() {
    return TRTCCloudVideoView(onViewCreated: (viewId) {
      if (TrtcUtils.trtcCloud != null) {
        TrtcUtils.trtcCloud!.startRemoteView(
            Config.userId2, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_SUB, viewId);
      }
    });
  }

  /// 权限提示
  showPermission(BuildContext context, {String? title, String? message}) {
    MyAlertDialog.showAlertDialog(
        context,
        MyAlertDialogData(
            title: title ?? "温馨提示",
            content: message,
            cancelButtonTitle: '取消',
            confrimButtonTitle: '去设置'), confrimFunc: () {
      openAppSettings();
      if (Navigator.canPop(context)) Navigator.pop(context);
    });
  }
}
